<template>
  <div class="pdf-viewer" ref="pdfViewer">
    <div v-for="page in renderedPages" :key="page" class="pdf-page">
      <canvas ref="pageCanvas" :data-page-number="page"></canvas>
    </div>
  </div>
</template>

<script>
import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf.mjs'
// import workerSrc from 'pdfjs-dist/legacy/build/pdf.worker.min.mjs'
import { nextTick } from 'vue'
const base = import.meta.env.VITE_BASE_PATH
pdfjsLib.GlobalWorkerOptions.workerSrc = base + "/js/pdf.worker.min.js"

let pdfDoc
export default {
  name: 'PDFViewer',
  props: {
    pdfUrl: {
      type: String,
      required: true,
    },
    scale: {
      type: Number,
      default: 1.5
    }
  },
  data() {
    return {
      numPages: 0,
      visiblePages: new Set(), // 用于追踪可见页面
      renderedPages: [], // 已渲染页面数组
    }
  },
  watch: {
    pdfUrl: {
      immediate: true,
      handler(newUrl) {
        if (newUrl) {
          this.loadPDF(newUrl)
        }
      },
    },
  },
  methods: {
    async loadPDF(pdfFile) {
      try {
        const loadingTask = pdfjsLib.getDocument(pdfFile)
        pdfDoc = await loadingTask.promise
        this.numPages = pdfDoc.numPages

        // 初始化页面列表
        this.renderedPages = Array.from({ length: this.numPages }, (_, i) => i + 1)
        await nextTick()
        this.setupObserver()
      } catch (error) {
        console.error('加载 PDF 失败:', error)
      }
    },
    setupObserver() {
      const observer = new IntersectionObserver(
        (entries) => {
          entries.forEach((entry) => {
            const pageNumber = parseInt(entry.target.dataset.pageNumber)
            if (entry.isIntersecting) {
              this.renderPage(pageNumber)
            }
          })
        },
        { root: this.$refs.pdfViewer, threshold: 0.1 },
      )

      this.$refs.pageCanvas.forEach((canvas) => {
        observer.observe(canvas)
      })
    },
    renderPage(pageNumber) {
      if (!this.visiblePages.has(pageNumber)) {
        this.visiblePages.add(pageNumber)

        pdfDoc.getPage(pageNumber).then((page) => {
          const canvas = this.$refs.pdfViewer.querySelector(
            `canvas[data-page-number="${pageNumber}"]`,
          )
          const context = canvas.getContext('2d')
          const viewport = page.getViewport({ scale: this.scale })

          canvas.width = viewport.width
          canvas.height = viewport.height

          const renderContext = {
            canvasContext: context,
            viewport,
          }
          page.render(renderContext)
        })
      }
    },
  },
}
</script>

<style>
.pdf-viewer {
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  height: 100vh;
  scroll-snap-type: y mandatory;
  gap: 20px;
}

.pdf-page {
  display: flex;
  justify-content: center;
  scroll-snap-align: start;
}

canvas {
  border: 1px solid #ddd;
}
</style>
